from gevent import monkey, spawn

monkey.patch_socket()
from gevent.queue import JoinableQueue
from .timer import Timer


class GPool:
    def __init__(self, data, concurrent=10, quit=7200 * 2):
        self.data = data
        self.timer = Timer()
        self.concurrent = concurrent
        self.quit = quit

        self.q = JoinableQueue()
        for item in self.data:
            self.q.put(item)


    def size(self):
        raise Exception("interface")

    def worker(self):
        try:
            while True:
                row = self.q.get()
                try:
                    self.do_work(row)
                finally:
                    self.q.task_done()
        except KeyboardInterrupt:
            self.q.task_done()

    def do_work(self, row):
        raise Exception("interface")

    def run(self):
        # self.q = JoinableQueue()
        # for item in self.data:
        #     self.q.put(item)
        #
        # self.timer.tic()
        # for i in range(self.concurrent):
        #     spawn(self.worker)
        # self.q.join(self.quit)
        # total = self.timer.toc()
        # print("total time:", total, "avg time:", total / self.size())
        # self.done()

        self.timer.tic()
        for i in range(self.concurrent):
            spawn(self.worker)
        self.q.join(self.quit)
        total = self.timer.toc()
        print("total time:", total, "avg time:", total / self.size())
        self.done()

    def done(self):
        print("all thing done")
